<template>
  <view class="entry-apply-container">
    <view v-if="isResubmit" class="reject-tip">拒绝原因：{{ rejectReason }}</view>
    <view class="title">配送员入驻申请</view>
    <form @submit.prevent="onSubmit">
      <view class="form-item">
        <text class="label">姓名</text>
        <input v-model="form.name" placeholder="请输入真实姓名" />
      </view>
      <view class="form-item">
        <view>
          <text>手机号</text>
          <button size="mini" open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber">获取手机号</button>
        </view>
        <input v-model="form.phone" placeholder="请输入手机号" type="number" />
      </view>
      <view class="form-item">
        <text class="label">身份证</text>
        <button @tap="chooseImage('idCard')">上传身份证照片</button>
        <image v-if="form.idCard" :src="form.idCard" class="preview-img" />
      </view>
      <view class="form-item">
        <text class="label">学生证</text>
        <button @tap="chooseImage('studentCard')">上传学生证照片</button>
        <image v-if="form.studentCard" :src="form.studentCard" class="preview-img" />
      </view>
      <view class="form-item">
        <text class="label">备注</text>
        <input v-model="form.remark" placeholder="备注（选填）" />
      </view>
      <button type="primary" form-type="submit" :loading="loading">提交申请</button>
    </form>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { submitDeliveryEntry, getLatestDeliveryEntry } from '@/api/deliveryEntry'
import { useUserStore } from '@/store/user'
import { uploadToOSS, fetchAndScheduleStsToken, clearStsTokenTimer } from '@/utils/oss'
import { onLoad } from '@dcloudio/uni-app'
import { getWechatPhoneNumber } from '@/api/wechat'


const userStore = useUserStore()
const form = ref({
  name: '',
  phone: '',
  idCard: '',
  studentCard: '',
  remark: ''
})
const loading = ref(false)
const isResubmit = ref(false)
const rejectReason = ref('')

onLoad(async (options) => {
  isResubmit.value = options.resubmit === '1'
  rejectReason.value = decodeURIComponent(options.reason || '')
  if (isResubmit.value && userStore.userInfo?.id) {
    try {
      const { data } = await getLatestDeliveryEntry(userStore.userInfo.id)
      if (data) {
        form.value.name = data.name || ''
        form.value.phone = data.phone || ''
        form.value.idCard = data.idCard || ''
        form.value.studentCard = data.studentCard || ''
        form.value.remark = data.remark || ''
      }
    } catch (e) {
      // ignore
    }
  }
})

onMounted(() => {
  fetchAndScheduleStsToken()
})
onUnmounted(() => {
  clearStsTokenTimer()
})

function decryptPhoneNumber(e) {
  if (e.detail.errMsg === 'getPhoneNumber:ok') {
    const code = e.detail.code
    // 调用后端获取手机号的接口
    getWechatPhoneNumber(code).then(res => {
      if(!res.data) {
        uni.showToast({ title: '获取手机号失败', icon: 'none' })
        return
      }
      form.value.phone = res.data
    })
  }
}

function chooseImage(type) {
  uni.chooseImage({
    count: 1,
    success: async (res) => {
      try {
        uni.showLoading({ title: '上传中...' })
        const url = await uploadToOSS(res.tempFilePaths[0])
        form.value[type] = url
        uni.showToast({ title: '上传成功', icon: 'success' })
      } catch (e) {
        uni.showToast({ title: '上传失败', icon: 'none' })
      } finally {
        uni.hideLoading()
      }
    }
  })
}

async function onSubmit() {
  if (!form.value.name || !form.value.phone || !form.value.idCard || !form.value.studentCard) {
    uni.showToast({ title: '请填写完整信息', icon: 'none' })
    return
  }
  loading.value = true
  try {
    await submitDeliveryEntry({
      ...form.value,
      deliveryUserId: userStore.userInfo?.id
    })
    uni.showToast({ title: '提交成功', icon: 'success' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/entry/pending' })
    }, 1000)
  } catch (e) {
    uni.showToast({ title: '提交失败', icon: 'none' })
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.entry-apply-container {
    padding: 32px 20px;
}
.form-item > view {
    display: flex;
    align-items: center;
    gap: 8rpx;
}
.reject-tip {
    color: #d9534f;
    font-size: 16px;
    margin-bottom: 12px;
    text-align: center;
    font-weight: bold;
}

.title {
    font-size: 22px;
    font-weight: bold;
    margin-bottom: 24px;
    text-align: center;
}

.form-item {
  margin-bottom: 32rpx;
}
.label {
  display: block;
  margin-bottom: 8rpx;
  color: #333;
}
input {
  width: 100%;
  border: 1px solid #eee;
  border-radius: 8rpx;
  padding: 16rpx;
  font-size: 28rpx;
}
.preview-img {
  width: 160rpx;
  height: 100rpx;
  margin-top: 8rpx;
}
</style>